import os

from PyQt5.QtCore import QThread, pyqtSignal, QDateTime, Qt
from PyQt5.QtGui import QIcon, QStandardItemModel, QStandardItem
from PyQt5.QtWidgets import QMainWindow, QApplication, QMenu, QAction, QStatusBar, QLabel, QSplitter, QWidget, \
    QVBoxLayout, QHBoxLayout, QComboBox, QPushButton, QTextEdit, QLineEdit, QFormLayout, QCheckBox, QFileDialog, \
    QTableView, QAbstractItemView, QHeaderView, QDialog
import json
import sys

from workspace.Project.UI.ui_base.py_ui_abstract import AbstractUiView


class UiComponentLogCfgForm(AbstractUiView):
    signal_ui_log_cfg = pyqtSignal(object)

    # 重写关闭窗体事件, 释放资源
    def closeEvent(self, event):
        self.signal_ui_log_cfg.emit({'Event': 'Close'})
        print('关闭日志配置窗口')
        event.accept()

    def __init__(self, cwd):
        super(UiComponentLogCfgForm, self).__init__(ui_name='ui_component_log_cfg', ui_version='v1.0.0')
        self._set_ui()
        self.setWindowTitle('过滤配置')
        self.resize(800, 400)
        self._cwd = cwd
        self.match_tableview_header = []
        self.match_tableview_items = []
        self.match_tableview_select = []

    def _set_ui(self):
        self._create_operate()
        self._create_result()

        main_layout = QVBoxLayout()
        main_layout.addWidget(self.op_widget)
        main_layout.addWidget(self.re_widget)
        self.setLayout(main_layout)

    def _create_operate(self):
        self.op_widget = QWidget()
        op_layout = QVBoxLayout()
        op_form_layout = QFormLayout()

        self.lb_match = QLabel('匹配规则')
        self.cb_match_type = QComboBox()
        self.cb_match_type.addItems(['完整匹配', '正则匹配'])
        self.cb_match_type.setCurrentIndex(0)
        self.cb_match_type.setFixedSize(120, 25)

        op_form_layout.addRow(self.lb_match, self.cb_match_type)

        self.bt_load_match = QPushButton('加载规则文件')
        self.bt_load_match.setFixedSize(120, 25)
        self.bt_load_match.clicked.connect(self._open_filter_cfg)
        self.bt_export_match = QPushButton('导出规则文件')
        self.bt_export_match.setFixedSize(120, 25)
        self.bt_export_match.clicked.connect(self._export_filter_cfg)

        op_Horizontal_layout = QHBoxLayout()
        op_Horizontal_layout.addLayout(op_form_layout)
        op_Horizontal_layout.addWidget(self.bt_load_match)
        op_Horizontal_layout.addWidget(self.bt_export_match)

        op_Horizontal_check_layout = QHBoxLayout()
        self.ckb_select_all = QCheckBox('全选')
        self.ckb_select_no = QCheckBox('取消全选')
        self.let_match_input = QLineEdit('添加匹配规则模板:Scc,TT,MCU/TT')
        self.bt_match_add = QPushButton('添加')
        self.bt_match_delete = QPushButton('删除')
        self.bt_match_update = QPushButton('修改')
        self.bt_match_refresh = QPushButton('刷新')

        op_Horizontal_check_layout.addWidget(self.ckb_select_all)
        op_Horizontal_check_layout.addWidget(self.ckb_select_no)
        op_Horizontal_check_layout.addWidget(self.let_match_input)
        op_Horizontal_check_layout.addWidget(self.bt_match_add)
        op_Horizontal_check_layout.addWidget(self.bt_match_delete)
        op_Horizontal_check_layout.addWidget(self.bt_match_update)
        op_Horizontal_check_layout.addWidget(self.bt_match_refresh)

        op_layout.addLayout(op_Horizontal_layout)
        op_layout.addLayout(op_Horizontal_check_layout)
        self.op_widget.setLayout(op_layout)

    def _create_result(self):
        self.re_widget = QWidget()
        re_layout = QVBoxLayout()
        # 先用文本编辑框占个位置
        self.table_view = QTableView()
        self.table_model = QStandardItemModel(0, 0, self)
        # self.table_model.setHorizontalHeaderLabels(['日期', '时间', '内容'])
        # self.te_result_log = QTextEdit()

        self.table_view.setEditTriggers(QAbstractItemView.NoEditTriggers)  # 禁用表格编辑功能
        self.table_view.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 设置表格自适应宽度
        self.table_view.setModel(self.table_model)
        re_layout.addWidget(self.table_view)
        self.re_widget.setLayout(re_layout)
        # self.re_widget.setM

    def _open_filter_cfg(self):
        open_file_path, filetype = QFileDialog.getOpenFileName(self, '打开文件', self._cwd, "Json Files (*.json)")
        match_json = {'filter_cfg': {
                'op_type': 'open',
                'filter_cfg_open': {
                    'file_type': filetype,
                    'file_path': open_file_path
                }
            }
        }
        self.signal_ui_log_cfg.emit(match_json)

    def _export_filter_cfg(self):
        export_file_path, filetype = QFileDialog.getSaveFileName(self, '保存文件', self._cwd, "Json Files (*.json)")
        match_json = {'filter_cfg': {
                'op_type': 'save',
                'filter_cfg_save': {
                    'file_type': filetype,
                    'file_path': export_file_path,
                    'file_data': self.match_tableview_items
                }
            }
        }
        self.signal_ui_log_cfg.emit(match_json)

    def _update_match_cfg(self, sender):
        if sender.text() == 'add':
            print("添加筛选")
        pass

    def update_match_tableview(self, **kwargs):
        if 'header_list' in kwargs:
            self.match_tableview_header = kwargs.get('header_list')
            self.table_model.setHorizontalHeaderLabels(self.match_tableview_header)

        if 'data_info' in kwargs:
            self.table_model.clear()
            self.table_model.setHorizontalHeaderLabels(self.match_tableview_header)
            for info in kwargs['data_info']:
                items_row = []
                for key in info:
                    items_row.append(QStandardItem(str(info[key])))
                self.table_model.appendRow(items_row)

            self.match_tableview_items = kwargs['data_info']
            self.match_tableview_select = self.match_tableview_items
            self.signal_ui_log_cfg.emit({'filter_select': self.match_tableview_select})


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app_path = os.getcwd()
    main = UiComponentLogCfgForm(app_path)
    main.show()
    sys.exit(app.exec())
